#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import cv2
import time
import traceback
import numpy as np
# from sklearn.datasets import load_iris
# from PIL import Image, ImageTk
# from skimage.data import page
from skimage.filters import (threshold_otsu, threshold_niblack, threshold_sauvola)


def manual_threshold(input_image, thresh):
    if input_image.ndim == 3:
        temp_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
        _, binary_image = cv2.threshold(temp_image, thresh, 255, cv2.THRESH_BINARY)
    else:
        _, binary_image = cv2.threshold(input_image, thresh, 255, cv2.THRESH_BINARY)
    return binary_image


def adaptive_threshold(input_image, max_val, th_type, bw_type):
    if input_image.ndim == 3:
        temp_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
        return cv2.adaptiveThreshold(temp_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,11,2)
    else:
        return cv2.adaptiveThreshold(input_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)


def otsu(input_image):
    if input_image.ndim == 3:
        temp_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
        _, binary_image = cv2.threshold(temp_image, 0, 255, cv2.THRESH_OTSU)
    else:
        _, binary_image = cv2.threshold(input_image, 0, 255, cv2.THRESH_OTSU)
    return binary_image


def sauvola(input_image):
    window_size = 35
    if input_image.ndim == 3:
        temp_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
        thresh_sauvola = threshold_sauvola(temp_image, window_size=window_size)
        binary_image = temp_image > thresh_sauvola
    else:
        thresh_sauvola = threshold_sauvola(input_image, window_size=window_size)
        binary_image = input_image > thresh_sauvola
    return binary_image


def niblack(input_image):
    window_size = 35
    if input_image.ndim == 3:
        temp_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
        thresh_niblack = threshold_niblack(temp_image, window_size=window_size, k=0.8)
        binary_image = temp_image > thresh_niblack
    else:
        thresh_niblack = threshold_niblack(input_image, window_size=window_size, k=0.8)
        binary_image = input_image > thresh_niblack
    return binary_image





